package com.lyb.springbootredisclient.common.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @author: lyb  2023/4/26 14:01
 */
@ControllerAdvice
public class BaseExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(BaseExceptionHandler.class);

    /**
     * 拦截 {@link RuntimeException} / {@link Exception} 异常信息，返回 “程序出现错误，请联系管理员” 信息
     *
     * @param
     * @return ExceptionResponse
     */
    @ExceptionHandler({RuntimeException.class,Exception.class})
    public ResponseEntity<ExceptionResponse> process(HttpServletRequest request, HandlerMethod method, Exception exception){
        if (LOGGER.isErrorEnabled()){
            LOGGER.error(exceptionMessage("error", request, method), exception);
        }
        ExceptionResponse exceptionResponse = new ExceptionResponse();
        exceptionResponse.setCode("error");
        exceptionResponse.setFailed(Boolean.TRUE);
        exceptionResponse.setType("error");
        exceptionResponse.setMessage(exception.toString()+"method:"+method.toString());
        return new ResponseEntity<>(exceptionResponse, HttpStatus.OK);
    }

    private String exceptionMessage(String message, HttpServletRequest request, HandlerMethod method) {
        return String.format(message + ", Request: {URI=%s, method=%s}, User: %s",
                request.getRequestURI(),
                Optional.ofNullable(method).map(HandlerMethod::toString).orElse("NullMethod"), "梁永补");
    }
}
